package com.naizhuai.util;

import android.content.Context;
import android.support.annotation.NonNull;

import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.List;

/**
 * @author：lichenxi
 * @date 2018/1/13 13
 * email：525603977@qq.com
 * Fighting
 */
public class PermissionRequest {
    private Context mContext;
    private static final int REQUEST_CODE = 100;

    public PermissionRequest(Context context) {
        mContext = context;
    }


    public void request(final PermissionCallback callback,String[]... permissionsArray) {
        AndPermission.with(mContext)
                .requestCode(REQUEST_CODE)
                .permission(permissionsArray)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        if(AndPermission.hasPermission(mContext,grantPermissions)) {
                            callback.onSuccessful();
                        } else {
                            AndPermission.defaultSettingDialog(mContext).show();
                        }
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        if(AndPermission.hasPermission(mContext,deniedPermissions)) {
                               callback.onSuccessful();
                        } else {
                            if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                                // 第一种：用默认的提示语。
                                AndPermission.defaultSettingDialog(mContext).show();
                            }else {
                                callback.onFailure();
                            }
                        }
                    }
                })
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(mContext, rationale).show();
                    }
                })
                .start();
    }
    public interface PermissionCallback {
        void onSuccessful();

        void onFailure();
    }
}
